﻿using Dto;
using IBLL;
using IDAL;
using Model;

namespace BLL
{
    public class HealthBLL : IHeathBLL
    {
        public HealthBLL(IHeathDAL<HealthModel>dal)
        {
            Dal = dal;
        }

        public IHeathDAL<HealthModel> Dal { get; }

        public Task<int> AddHeath(HealthModel health)
        {
            string a=DateTime.Now.ToString("yyyyMMdd");
            string b = new Random().Next(100,999).ToString();
            health.Bh=a+b;
            return Dal.AddAsync(health);
        }

        public Task<int> DeleteRangeHealth(string idstring)
        {
           List<int>ints=idstring.ToString().Split(',').Select(a=>Convert.ToInt32(a)).ToList();
            var emplist = Dal.GetAllAsync().Where(a => ints.Contains(a.Id));
            foreach (var item in emplist)
            {
                item.IsDelete = true;
                item.DeleteDate = DateTime.Now;
            }
            return Dal.UpdateRangeAsync(emplist.ToList());
        }

        public List<HealthModel> GetHealthList()
        {
            return Dal.GetAllAsync().ToList();
        }

        public HealthShowDto HealthShow(string? name, int pageindex, int pagesize)
        {
            var sql = from a in Dal.GetAllAsync().Where(a=>a.IsDelete==false)
                      select new 
                      {
                          a.Id,
                          a.HelthName,
                          a.Bh,
                          a.Money,
                          a.People,
                          a.Hour,
                          a.Xm,
                          a.State,
                          a.IsDelete
                      };
            if (!string.IsNullOrEmpty(name)) 
            {
                sql=sql.Where(a=>a.HelthName.Contains(name));
            }
            var c = sql.Count();
            var m=sql.OrderBy(sql=>sql.Id).Skip((pageindex-1)*pagesize).Take(pagesize);
            return new HealthShowDto { Count = c,Members=m };
        }

        public Task<int> UpdateRangeState(string idstring)
        {
            List<int>ints=idstring.ToString().Split(',').Select(a=>Convert.ToInt32(a)).ToList();
            var emplist=Dal.GetAllAsync().Where(a=>ints.Contains(a.Id));
            foreach (var item in emplist)
            {
                item.State = item.State == 1 ? 2 : 1;
                item.UpdateDate = DateTime.Now;
            }
            return Dal.UpdateRangeAsync(emplist.ToList());
        }

    }
}
